import {  createSlice, Draft, PayloadAction } from "@reduxjs/toolkit";
import { persistReducer } from "redux-persist";
import storage from "redux-persist/lib/storage";
// 令牌类型
export interface Credentials {
    token: string;
    refresh_token: string;
}

// 初始状态
const initialState: Credentials = {
    token: "",
    refresh_token: "",
};


// Draft 是 immer 库中的一个核心类型，而 @reduxjs/toolkit 内部集成了 immer
// Draft 类型允许开发者以可变的方式编写代码， immer 会在底层自动将这些操作转换为不可变的更新
// 状态切片
const loginSilce = createSlice({
    name: "credentials",
    initialState: initialState,
    reducers: {
        // 保存登录凭证 纯函数
        saveCredentials: (state: Draft<Credentials>, action: PayloadAction<Credentials>) => {
            console.log('saveCredentials',action)
            state.token = action.payload.token;
            state.refresh_token = action.payload.refresh_token;
        },
        // 重置登录凭据
        resetCredentials(state: Draft<Credentials>) {
            state.token = "";
            state.refresh_token = "";
        },
    }
    
});

export const { saveCredentials,resetCredentials } = loginSilce.actions;
// export default loginSilce.reducer;

const persistCredentialsReducer = persistReducer(
    { key: "credentialsReducer", storage },
    loginSilce.reducer
);
export default persistCredentialsReducer;